/**
 * canvas 功能封装
 */
class NCanvas {
  constructor(dom = document.createElement("canvas")) {
    this.dom = dom;
    this.canvasContext = this.dom.getContext("2d");
  }
  /**
   * 图片绘制
   * @param {Object} img
   * @param {Object} xmin
   * @param {Object} xmax
   * @param {Object} ymin
   * @param {Object} ymax
   */
  drawImg(
    img,
    option = {
      x: 0,
      y: 0,
      width: 100,
      height: 100,
    }
  ) {
    this.canvasContext.drawImage(
      img,
      option.x,
      option.y,
      option.width,
      option.height
    );
  }
  /**
   * 文字绘制
   */
  drawText(
    text,
    option = {
      x: 50,
      y: 50,
    },
    style = {
      font: "10px 宋体",
      textAlign: "center",
      fillStyle: "#fff",
    }
  ) {
    Object.assign(this.canvasContext, style);
    this.canvasContext.fillText(text + "", option.x, option.y);
  }
  /**
   * 生成图片链接
   */
  toDataUrl() {
    return this.dom.toDataURL("images/png");
  }
  getData() {
    //获取画布的宽和高
    let width = this.dom.getAttribute("width");
    let height = this.dom.getAttribute("height");
    return this.canvasContext.getImageData(0, 0, width, height);
  }
}

class NImg {
  constructor(
    dom = document.createElement("img"),
    option = { onload: () => {} }
  ) {
    this.dom = dom;
    if (option.src) {
      this.dom.src = option.src;
    }
    this.dom.setAttribute("crossOrigin", "Anonymous");
    this.dom.onload = function () {
      // 图片实际宽度
      this.naturalWidth;
      // 图片实际高度
      this.naturalHeight;
      // 加载完成执行
      option.onload(this);
    };
  }
}

export default {
  NCanvas,
  NImg,
};
